<template>
  <div id="home">
    <!-- header -->
    <home-header></home-header>
    <!-- catetab -->
    <van-tabs class="catetabs" v-model:active="active">
      <van-tab
        v-for="(item, index) in categoryList"
        :key="index"
        :title="item.name"
        :to="'/home/itemlist/' + item.id"
      >
      </van-tab>
    </van-tabs>
    <scroll class="content" ref="scroll">
      <router-view></router-view>
    </scroll>
    <!-- footer -->
  </div>
</template>

<script>
import Scroll from "components/common/Scroll.vue";
import HomeHeader from "components/home/HomeHeader";
import { getIndexData } from "network/home";
export default {
  name: "Home",
  components: {
    Scroll,
    HomeHeader,
  },
  data() {
    return {
      categoryList: [],
      active: 0,
    };
  },
  // computed: {
  //   imgOnload() {
  //     return this.$store.state.imgOnload;
  //   },
  // },
  // watch: {
  //   imgOnload() {
  //     console.log('加载了');
  //     this.refresh()
  //     this.$refs.scroll.refresh();
  //   },
  // },
  created() {
    this.getIndexData();
    let timeInterval = setInterval(() => {
      if (this.categoryList.length > 0) {
        clearInterval(timeInterval);
        this.keepActive();
      }
    }, 50);
  },
  mounted() {
    const refresh = this.debounce(this.$refs.scroll.refresh,50)

    this.$bus.$on("itemImageLoad", () => {
      refresh()
    });
  },
  methods: {
    getIndexData() {
      getIndexData()
        .then((res) => {
          this.categoryList = res.data.data.categoryList;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    keepActive() {
      for (let i = 0; i < this.categoryList.length; i++) {
        // console.log('......');
        if (this.categoryList[i].id == this.$route.params.id) {
          this.active = i;
          break;
        }
      }
    },
    debounce(func, delay) {
      let timer = null;
      return function (...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(this, args);
        }, delay);
      };
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#home {
  position: relative;
  height: 100vh;
  overflow: hidden;
}
.content {
  position: absolute;
  left: 0;
  right: 0;
  top: 74px;
  bottom: 50px;
}
.catetabs {
  position: sticky;
  top: 44px;
  background-color: #fff;
  z-index: 3;
}
</style>